﻿using DA.Core.Common;
using DA.Core.Mes;
using DA.Core.Plcs;
using DA.Core.WorkFlows;
using DA.Model.Common;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace DA.Core.Stations
{
    public class StationManager
    {
        private Configurations configurations;
        private IContainerProvider containerProvider;
        private PlcManager plcManager;
        private ClientManager clientManager;

        [Unity.Dependency]
        public IEnumerable<IWorkFlow> wrokFlows;
        public StationManager(IContainerProvider containerProvider, Configurations configurations, PlcManager plcManager, ClientManager clientManager)
        {
            this.configurations = configurations;
            this.containerProvider = containerProvider;
            this.plcManager = plcManager;
            this.clientManager = clientManager;
        }
        public void Init()
        {
            try
            {
                //关闭时清空所有的资源
                //plcManager.Init();
                //clientManager.Init();

                configurations?.Appsetting?.Stations?.ForEach(p =>
                {
                    var station = containerProvider.Resolve<IStation>();
                    Task.Run(() =>
                    {
                        station.WorkFlow= wrokFlows.FirstOrDefault(c => c.FlowName == p.FlowName);
                        var plc = plcManager.PlcDics.FirstOrDefault(c => c.Key == p.PlcID).Value;
                        var client = clientManager.ClientDics.FirstOrDefault(c => c.Key == p.MesID).Value;
                        station.Init(plc, client, p);
                    });
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}
